# 店铺信息
import banner as banner
from django.shortcuts import render
from django.http import HttpResponse
from django.core.paginator import Paginator
from django.db.models import Q
from datetime import datetime
from ..models import Shop
import time


def index(request, pIndex=1):
    smod = Shop.objects
    slist = smod.filter(status__lt=9)
    mywhere = []
    kw = request.GET.get('keyword', None)
    if kw:
        slist = slist.filter(Q(name__contains=kw))  # 模糊查询
        mywhere.append('keywprd=' + kw)
    status = request.GET.get('status', '')
    if status != '':
        slist = slist.filter(status=status)
        mywhere.append("status=" + status)
    slist = slist.order_by('id')
    pIndex = int(pIndex)  # 执行分页操作
    page = Paginator(slist, 5)  # 5条数据为分页
    maxpages = page.num_pages  # 得到页数
    if pIndex > maxpages:  # 判断当前页是否越界
        pIndex = maxpages
    if pIndex < 1:
        pIndex = 1
    list2 = page.page(pIndex)  # 获取当前页数据
    plist = page.page_range  # 获取页码列表信息
    context = {"shoplist": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages, 'mywhere': mywhere}
    return render(request, "myadmin/shop/index.html", context)


def add(request):
    """加载信息"""
    return render(request, "myadmin/shop/add.html")


def insert(request):
    """添加信息"""
    try:
        # 文件上传
        myfile = request.FILES.get('cover_pic', None)
        if not myfile:
            return HttpResponse("没有店铺封面上传文件信息")
        cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/shop/" + cover_pic, "wb+")
        for chunk in myfile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()
        myfile = request.FILES.get('banner_pic', None)
        if not myfile:
            return HttpResponse("没有店铺封面上传文件信息")
        banner_pic = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/shop/" + banner_pic, "wb+")
        for chunk in myfile.chunks():  # 分块写入文件
            destination.write(chunk)
        destination.close()

        # 实例化封装信息
        ob = Shop()
        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']
        ob.cover_pic = cover_pic
        ob.banner_pic = banner_pic
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "添加成功！"}
    except Exception as err:
        print(err)
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context=context)


def delete(request, sid=0):
    """删除信息"""
    try:
        ob = Shop.objects.get(id=sid)
        ob.status = 9
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info':"删除成功！"}
    except Exception as err:
        print(err)
        context = {'info':"删除失败！"}
    return render(request, "myadmin/info.html", context=context)


def edit(request, sid=0):
    """编辑信息"""
    try:
        ob = Shop.objects.get(id=sid)
        context = {'shop': ob}
        return render(request, "myadmin/shop/edit.html", context=context)
    except Exception as err:
        print(err)
        context = {'info': "没有找到要修改的信息！"}
        return render(request, "myadmin/info.html", context=context)


def update(request, sid=0):
    """更新信息"""
    try:
        ob = Shop.objects.get(id=sid)
        ob.status = request.POST['status']
        ob.name = request.POST['name']
        ob.address = request.POST['address']
        ob.phone = request.POST['phone']
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "修改成功！"}
    except Exception as err:
        print(err)
        context = {'info': "修改失败！"}
    return render(request, "myadmin/info.html", context=context)
